﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using FileManagerLibrary;
using System.Threading;
using Logging;
using FileManagerLibrary.Base.JobManagers;
using FileManagerLibrary.Base.FileBase;
using FileManagerService.Properties;

namespace FileManagerService
{
    public partial class FileManagerService : ServiceBase
    {
        ScheduledJobManager winService;
        FileWatcherManager watcher;

        public FileManagerService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            winService = new ScheduledJobManager();
            watcher = new FileWatcherManager();
            Logger.StaticLogger.AddAuditLogEntry("Starting the Service");
            winService.StartService();
            watcher.WatcherEnabled = true;
        }

        protected override void OnStop()
        {
            winService.StopTimer();
            watcher.WatcherEnabled = false;
            Logger.StaticLogger.AddAuditLogEntry("Stopping the Service");
            base.OnStop();
        }

        protected override void OnPause()
        {
            winService.StopTimer();
            watcher.WatcherEnabled = false;
            Logger.StaticLogger.AddAuditLogEntry("Pausing the Service");
            base.OnPause();
        }

        protected override void OnContinue()
        {
            winService = new ScheduledJobManager();
            watcher = new FileWatcherManager();
            Logger.StaticLogger.AddAuditLogEntry("Continue the Service");
            winService.StartService();
            watcher.RefreshAllWatchers();
            watcher.WatcherEnabled = true;
            base.OnContinue();
        }

        #region WindowsService Debug Helper. This will help to debug the service as well as to run the application when deployed in services.svc

        public static void Main(string[] args)
        {
            try
            {
                /* Modified the windows service autogenerated code so that it 
                 * will run as acommand prompt app during debug 
                 * and as a windows service if started from Services.msc.
                 * With this change in application, if you double click it will open a 
                 * command prompt asking to debug and installation instructions. 
                 */
                var FileManagerService = new FileManagerService();
                if (Environment.UserInteractive)
                {
                    Console.WriteLine("Starting Windows Service in Console Mode.");
                    Console.WriteLine("To use this application as a Windows service,");
                    Console.WriteLine("you must register the executable as a Windows service");
                    Console.WriteLine("using 'InstallUtil' and start from Services.msc.");
                    Console.WriteLine("Also debug as a console application from VS.Net IDE.");
                    Console.WriteLine("Press Enter when done to terminate.");
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                    Logging.Logger.EnableFileModeLogging(FileOperations.GetAppSettingsFolderRoot() + "\\" + Settings.Default.ApplicationLogLocation);
                    FileManagerService.OnStart(args);
                    Console.ReadLine();
                    FileManagerService.OnStop();
                }
                else
                {
                    ServiceBase[] ServicesToRun;
                    ServicesToRun = new ServiceBase[] 
			    { 
				    new FileManagerService() 
			    };
                    Logging.Logger.EnableFileModeLogging(FileOperations.GetAppSettingsFolderRoot() + "\\" + Settings.Default.ApplicationLogLocation);
                    ServiceBase.Run(ServicesToRun);
                }

                /* DONOT UNCOMMENT. WILL LAUNCH DEBUGGER DURING RUN.
                 * Adding the Debugger.Launch condition to attach a debugger to the published service when it is about to start.
                 * Note: Remember to either remove this code before you release to production or 
                 * do not release to production only in the 'Release' configuration.
                 */
                //#if DEBUG
                //    System.Diagnostics.Debugger.Launch();
                //#endif
            }
            catch (Exception ex)
            {
                Logger.StaticLogger.AddErrorLogEntry(ex, "Critical: Service UnhandledException Occured.");
            }
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            Logger.StaticLogger.AddErrorLogEntry(ex, "Critical: Service UnhandledException Occured.");
        }

        #endregion
    }
}
